import logging
from seleniumwire import webdriver as wire_webdriver
from selenium.common.exceptions import UnexpectedAlertPresentException,WebDriverException
chrome_options = wire_webdriver.ChromeOptions()
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
chrome_options.add_argument("--ignore-certificate-errors")  # 忽略证书错误警告
chrome_options.add_argument("--ignore-ssl-errors")  # 忽略SSL错误警告
chrome_options.add_argument('blink-settings=imagesEnabled=false') # 不加载图片
# chrome_options.add_argument('--headless')  # 设置为无头模式

# 速度稍慢
def keep_token_alive(user_agent,token,cookie):
    url = f'https://mp.weixin.qq.com/cgi-bin/settingpage?t=setting/index&action=index&token={token}&lang=zh_CN'
    # url = f'https://mp.weixin.qq.com/cgi-bin/home?t=home/index&token=104630102&lang=zh_CN'
    # 设置打开浏览器下载文件的目录，例如打开有pdf的网页时会自动下载pdf
    prefs = {
    "download.default_directory": './testwechat',
    "download.prompt_for_download": False,
    "download.directory_upgrade": True,
    "safebrowsing.enabled": True,
    }
    chrome_options.add_experimental_option("prefs", prefs)
    chrome_options.add_argument("--user-agent=" + user_agent) 
    
    # 创建Chrome WebDriver实例
    driver = wire_webdriver.Chrome(options=chrome_options)
    cookies = cookie.split(';')
    
    try:
        # 打开网页
        driver.get(url)
        for cookie_ in cookies:
            cookie_dict = {}
            idx_eq = cookie_.find('=')
            cookie_key = cookie_[:idx_eq].strip()
            cookie_value = cookie_[idx_eq+1:].strip()
            cookie_dict['name'] = cookie_key
            cookie_dict['value'] = cookie_value
            driver.add_cookie(cookie_dict)
    
        # 加载完cookie后再次加载网页
        driver.get(url)
        logging.error('正在保持Token存活...')
        # TODO 联动数据库的is_zombie字段，如果is_zombie=1,就停止此函数
        while True:
            pass

    except UnexpectedAlertPresentException as e:
        logging.error('弹窗：')
        logging.error(e.alert_text)
        return []
    except WebDriverException as e:
        logging.error(f'[{url}]不可达!')
        return ["can't reach"]
    except Exception as e:
        logging.error('spider_by_selenium_wire wrong:')
        logging.error(e)
        return []
    finally:
        if driver:
            driver.quit()

if __name__ == "__main__":
    cookie = 'pgv_pvid=6674370122; RK=BeHhkzfcSi; ptcz=d6a912cf360068ad80d096aa6ba2bf3b50e831cb20f1d281c50fb6635c019630; Qs_lvt_323937=1692089857; Qs_pv_323937=1972696628665984500; pac_uid=0_05c866c98a5da; iip=0; _qimei_uuid42=17c1b08141a1005755c6fb37f6b5fb59aa1343e21c; _qimei_fingerprint=373c5bebdee985a6979a0fde94db292e; _qimei_q36=; _qimei_h38=8f9581b755c6fb37f6b5fb590200000f717c1b; rewardsn=; wxtokenkey=777; ua_id=liUBhov6PAUr5eU2AAAAAIRTVMGJKO7S2E2-emuS3Cw=; wxuin=15172500468962; _clck=o309pp|1|flm|0; uuid=223979ffedbef6edd395c7156869a6a8; bizuin=3918696977; ticket=000a33b58985a1dd4d8604e422438d1aaf3a1092; ticket_id=gh_1469fb030616; slave_bizuin=3918696977; cert=kS9_cHBtG_VVTtf6HuruFIvB1O_2pklI; noticeLoginFlag=1; remember_acct=398312721%40qq.com; rand_info=CAESINftIqp9uselp6sADy8N5XKmpGpyXWzOE7+3O5JsjhLD; data_bizuin=3918696977; data_ticket=X2IRk2HEK/EOBXQUtqQP6Byit9CvRz5437KZAx3GA8IuI0wc4G5WcZ60pgwNJp4w; slave_sid=YW1DUk1lNW9xQlNkM3NxaFl3X29hRGZiWVpDWWVEcF91eWNGQUdDUm5ZbjVmdVpCejB0bElPSGUweU9lVjd6amg3MjlOelMybHY4aWdRMGhBckhEUDMyR01pWjU1SzlTNjJuQ0RnYUx6aWJhMkpNZUNMT0cwWFBMNEdsSVRpVWdkNVdFemlFRUprTFk2bDRt; slave_user=gh_1469fb030616; xid=217a39b4b95334d4ecf96fefc5c6d9cd; openid2ticket_oEZKS6cJsW3K-PRSfMvcC_TUt40s=OXwHcyXBwU7dsSHDobBixxjpWiDMOuM6WBS7yCcYCbA=; mm_lang=zh_CN; _clsk=1vhladk|1715246606593|15|1|mp.weixin.qq.com/weheat-agent/payload/record'
    keep_token_alive('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36 Edg/124.0.0.0',
                     token='104630102',cookie=cookie)